import KeyList from "./key.list.js"
import KeyDetail from "./key.detail.js"

let timer = null
export default class Data extends Element {

    constructor() {
        super()
        document.on("db-change", (evt) => {
            this.db = evt.data.db
            try {
                document.$("#search").value = ""
            } catch (e) {
            }
        })
    }

    w = 225

    componentDidMount() {
        document.$(".frame-warp").on("mousemove", evt => {
            if (this.move) {
                let w = evt.x
                if (w >= 480) {
                    w = 480
                }
                if (w <= 225) {
                    w = 225
                }
                clearTimeout(timer)
                this.componentUpdate({
                    w
                })

            }
        })
        document.$(".frame-warp").on("mouseup", evt => {
            this.move = false
        })
    }

    move = false
    db = "0"

    render() {
        return <div>
            <div class={"left"} style={"width:" + this.w + "px"}>
                <div class={"keys-search"}>
                    <div class={"search-input-container"}>
                        <input type="text"
                               id={"search"}
                               onChange={(...args) => this.searchInputChange(...args)}
                               placeholder={"请输入表达式搜索"} onClick={() => {
                            this.post(new Event("search", {bubbles: true, data: {key: this.key}}))
                        }} class={"search-input"}/>
                    </div>
                    <div class={"search-icon"}>
                        <i class={"icon icon-magnify"}></i>
                    </div>
                </div>
                <div class={"keys-container"}>
                    {this.renderKeys()}
                </div>
            </div>
            <div class={"resize-line"} style={"left:" + this.w + "px"}></div>
            <div class={"right"} style={"width:calc(100% - " + this.w + "px)"}>
                <KeyDetail/>
            </div>
        </div>
    }

    ["on mousedown at .resize-line"](evt, ele) {
        this.move = true
    }

    ["on mouseup at .resize-line"](evt) {
        this.move = false
    }

    searchInputChange(evt, ele) {
        this.key = ele.value
        clearTimeout(timer)
        timer = setTimeout(() => {
            this.post(new Event("search", {bubbles: true, data: {key: ele.value}}))
        }, 500)
    }


    renderKeys() {
        return [
            <div class={"key-item-root"}>
                <i class={"icon icon-database"}></i>
                {"数据库 " + this.db}
            </div>,
            <KeyList/>,
            <div style={"height:5px"}></div>
        ]
    }
}